/*
 * Copyright (C) 2011  John Lawrence thegordo.john at gmail.com
 * Licensed under GPLv3 or later. see http://www.gnu.org/copyleft/gpl.html
 */

package org.jklawrencefam.server.smtp.state;

import org.jklawrencefam.Util.Parameters;
import org.jklawrencefam.authentication.User;
import org.jklawrencefam.model.email.Address;
import org.jklawrencefam.model.email.Message;
import org.jklawrencefam.server.smtp.command.SmtpCommand;

/**
 * User: John Lawrence
 * Date: 5/29/11
 * Time: 1:27 AM
 */
public class SmtpState {
    private SmtpCommand currentCommand;
    private SmtpCommand lastCommand;
    private Parameters parameters;
    private Message message;

    public SmtpState() {
        parameters = new Parameters();
    }

    public SmtpCommand getCurrentCommand() {
        return currentCommand;
    }

    public void setCurrentCommand(SmtpCommand currentCommand) {
        lastCommand = this.currentCommand;
        this.currentCommand = currentCommand;
        currentCommand.setState(this);
        currentCommand.doProcess();
    }

    public Message getMessage() {
        if (message == null) {
            message = new Message();
        }
        return message;
    }

    public void clearMessage() {
        message = null;
    }

    public SmtpCommand getLastCommand() {
        return lastCommand;
    }

    public void setParameter(StateParameters key, Object value) {
        parameters.setParameter(key, value);
    }

    @SuppressWarnings({"UnusedParameters"})
    public <T> T getParameter(StateParameters key, Class<T> classs) {
        return parameters.getParameter(key, classs);
    }

    public Mode getServerMode() {
        User myUser = getParameter(StateParameters.User, User.class);
        if (myUser != null && myUser.isValid()) {
            return Mode.Relay;
        }
        return Mode.Accept;
    }

    public void setMessageData(String messageBody) {
        getMessage().setData(messageBody);
    }

    public void setFrom(Address from) {
        getMessage().setFrom(from);
    }

    public void addRecipient(Address recipient) {
        getMessage().addRecipient(recipient);
    }

    public enum Mode {
        Accept,
        Relay
    }
}
